package cn.four.hqServer.modules.cardBinding.service.impl;

import cn.four.hqServer.common.entity.HqCardInfo;
import cn.four.hqServer.common.entity.HqUserInfo;
import cn.four.hqServer.common.enums.CardStatusEnum;
import cn.four.hqServer.common.result.Result;
import cn.four.hqServer.modules.balance.service.LycCardInfoService;
import cn.four.hqServer.modules.balance.service.LycUserInfoService;
import cn.four.hqServer.modules.cardBinding.mapper.CardWithdrawMapper;
import cn.four.hqServer.modules.cardBinding.service.CardWithdrawService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author znb
 * @since 2023-02-23
 */
@Service
public class CardWithdrawServiceImpl extends ServiceImpl<CardWithdrawMapper, HqUserInfo> implements CardWithdrawService {

    @Resource
    private LycUserInfoService userInfoService;

    @Resource
    private LycCardInfoService cardInfoService;

    /**
     * 注销卡
     * @param cardId
     * @return
     */
    @Override
    @Transactional
    public Result withdraw(String cardId) {

        HqCardInfo cardInfo = cardInfoService.getById(cardId);
        /**
         * 余额小于0，或者透支，冻结均视为银行卡状态异常，不能操作
         */
        if(cardInfo.getBalance().compareTo(new BigDecimal(0)) == -1 ||
                cardInfo.getState()== CardStatusEnum.freeze.getCode() ||
                cardInfo.getState()== CardStatusEnum.overdraft.getCode())
            return Result.error("银行卡状态异常，不能操作");

        if(cardInfo.getBalance().compareTo(new BigDecimal(0)) > 0 )
            return Result.error("仍有余额，余额清零才可重新开户或注销，你可以去取款");

        /**
         * 设置状态码为注销
         */
        cardInfoService.update(new UpdateWrapper<HqCardInfo>().eq("card_id", cardId)
                .set("state", CardStatusEnum.logout.getCode()));

//        //测试业务出现异常，数据库是否回滚
//        int a =1/0;
        return Result.success("注销成功");
    }
}
